package com.wendu.oa.api.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wendu.oa.common.Constants;
import com.wendu.oa.common.CurrentUser;
import com.wendu.oa.common.Result;
import com.wendu.oa.common.TokenUtils;
import com.wendu.oa.dto.MenuDto;
import com.wendu.oa.exception.BusinessException;
import com.wendu.oa.exception.SysException;
import com.wendu.oa.service.security.HomeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/security/home")
public class HomeController {

    @Autowired
    private HomeService homeService;

    @GetMapping("/menu-list")
    public Result menuList(HttpServletRequest request){
        try{
            String token = request.getHeader(Constants.HEADER_TOKEN);
            CurrentUser currentUser = TokenUtils.getCurrentUser(token);
            List<MenuDto> list = homeService.getMenuList(currentUser.getUserId());
            return Result.OK(list);
        }catch(BusinessException e){
            return Result.err(Result.CODE_ERR_BUSINESS,e.getMessage());
        }catch (SysException e){
            log.error("系统错误！",e);
            return Result.err(Result.CODE_ERR_SYS, "系统升级中...");
        }catch (Exception e){
            log.error("系统错误！",e);
            return Result.err(Result.CODE_ERR_SYS, "系统升级中...");
        }
    }

    @GetMapping("/curr-user")
    public Result currentUser(HttpServletRequest request){


        try{
            String token = request.getHeader("Token");
            CurrentUser currentUser = TokenUtils.getCurrentUser(token);

            return Result.OK(currentUser);
        }catch(BusinessException e){
            return Result.err(Result.CODE_ERR_BUSINESS,e.getMessage());
        }catch (SysException e){
            log.error("系统错误！",e);
            return Result.err(Result.CODE_ERR_SYS, "系统升级中...");
        }catch (Exception e){
            log.error("系统错误！",e);
            return Result.err(Result.CODE_ERR_SYS, "系统升级中...");
        }

    }

    @DeleteMapping("/curr-user")
    public Result exit(HttpServletRequest request){
        try{
            String token = request.getHeader(Constants.HEADER_TOKEN);
            TokenUtils.removeToken(token);
            return Result.OK();
        }catch(BusinessException e){
            return Result.err(Result.CODE_ERR_BUSINESS,e.getMessage());
        }catch (SysException e){
            log.error("系统错误！",e);
            return Result.err(Result.CODE_ERR_SYS, "系统升级中...");
        }catch (Exception e){
            log.error("系统错误！",e);
            return Result.err(Result.CODE_ERR_SYS, "系统升级中...");
        }
    }


}
